package top.bug.blog.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import top.bug.blog.common.UserContext;
import top.bug.blog.constant.UserConstants;
import top.bug.blog.utils.StrUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author <a href="https://github.com/jiusi66">九思.</a>
 * @email 10837907@qq.com
 * @from <a href="https://www.52bug.top">递归茶馆-www.52bug.top</a>
 * @description 用户信息拦截器
 */
@Component
public class UserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 在请求处理之前进行拦截处理
        HttpSession session = request.getSession();
        String userId = String.valueOf(session.getAttribute(UserConstants.USER_LOGIN_KEY));
        // 保存用户id 到 ThreadLocal
        if (StrUtils.isNotBlank(userId)) {
            UserContext.setUserId(userId);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清理 ThreadLocal
        UserContext.clear();
    }
}
